/**
 * TimerJobController.java
 * Created at 2017-09-14
 * Created by Jackie liu
 * Copyright (C) 2014, All rights reserved.
 */
package com.yunfeisoft.controller.base;

import com.applet.base.BaseController;
import com.applet.utils.*;
import com.yunfeisoft.model.TimerJob;
import com.yunfeisoft.service.inter.DataService;
import com.yunfeisoft.service.inter.TimerJobService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>ClassName: TimerJobController</p>
 * <p>Description: 定时器任务Controller</p>
 * <p>Author: Jackie liu</p>
 * <p>Date: 2017-09-14</p>
 */
@Controller
public class TimerJobController extends BaseController {

    @Autowired
    private TimerJobService timerJobService;
    //@Autowired
    //private ScheduleManager scheduleManager;
    @Autowired
    private DataService dataService;

    /**
     * 添加定时器任务
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/save", method = RequestMethod.POST)
    @ResponseBody
    public Response save(TimerJob record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "name", "请输入名称");
        validator.required(request, "cron", "请输入cron表达式");
        validator.required(request, "className", "请输入类全名");
        validator.required(request, "methodName", "请输入执行方法名");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        boolean exists = timerJobService.isDuplicateName(record.getId(), record.getName());
        if (exists) {
            return ResponseUtils.warn("该名称已经存在");
        }

        exists = timerJobService.isDuplicateClassAndMethodName(record.getId(), record.getClassName(), record.getMethodName());
        if (exists) {
            return ResponseUtils.warn("该{类名+方法名}已经存在");
        }

        record.setId(KeyUtils.getKey());
        record.setState(TimerJob.Status.NO_JOIN.getValue());
        timerJobService.save(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 修改定时器任务
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modify(TimerJob record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "name", "请输入名称");
        validator.required(request, "cron", "请输入cron表达式");
        validator.required(request, "className", "请输入类全名");
        validator.required(request, "methodName", "请输入执行方法名");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        boolean exists = timerJobService.isDuplicateName(record.getId(), record.getName());
        if (exists) {
            return ResponseUtils.warn("该名称已经存在");
        }

        exists = timerJobService.isDuplicateClassAndMethodName(record.getId(), record.getClassName(), record.getMethodName());
        if (exists) {
            return ResponseUtils.warn("该{类名+方法名}已经存在");
        }

        timerJobService.modify(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 查询定时器任务
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/query", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response query(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        TimerJob record = timerJobService.load(id);
        if (record != null) {
            String errorMessage = dataService.loadByRefId(id);
            record.setErrorMessage(errorMessage);
        }
        return ResponseUtils.success(record);
    }

    /**
     * 分页查询定时器任务
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response list(HttpServletRequest request, HttpServletResponse response) {
        String name = ServletRequestUtils.getStringParameter(request, "name", null);
        Map<String, Object> params = new HashMap<String, Object>();
        initParams(params, request);
        params.put("name", name);
        Page<TimerJob> page = timerJobService.queryPage(params);
        return ResponseUtils.success(page);
    }

    /**
     * 加入任务到容器
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/join", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response join(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        TimerJob timerJob = timerJobService.load(id);
        if (timerJob == null) {
            return ResponseUtils.warn("参数错误");
        }
        if (timerJob.getState() != TimerJob.Status.NO_JOIN.getValue()) {
            return ResponseUtils.warn("已加入的任务无法重新加入");
        }
        timerJob.setState(TimerJob.Status.JOIN.getValue());
        /*ScheduleJob scheduleJob = FastJsonUtils.jsonToObj(timerJob.toString(), ScheduleJob.class);
        try {
            scheduleManager.addJob(scheduleJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResponseUtils.warn("加入失败");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return ResponseUtils.warn("加入失败");
        }*/
        timerJobService.modify(timerJob);
        return ResponseUtils.success("加入成功");
    }

    /**
     * 更新任务调度时间
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/modifyCron", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response modifyCron(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        TimerJob timerJob = timerJobService.load(id);
        if (timerJob == null) {
            return ResponseUtils.warn("参数错误");
        }
        if (timerJob.getState() == TimerJob.Status.NO_JOIN.getValue()) {
            return ResponseUtils.warn("未加入运行的任务无法更新调度时间");
        }

        /*ScheduleJob scheduleJob = FastJsonUtils.jsonToObj(timerJob.toString(), ScheduleJob.class);
        try {
            scheduleManager.updateJobCron(scheduleJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResponseUtils.warn("更新任务调度时间失败");
        }*/
        return ResponseUtils.success("更新任务调度时间成功");
    }

    /**
     * 移除容器中的任务，不删除数据库中的数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/timerJob/removeJob", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response removeJob(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        TimerJob timerJob = timerJobService.load(id);
        if (timerJob == null) {
            return ResponseUtils.warn("参数错误");
        }

        if (timerJob.getState() == TimerJob.Status.NO_JOIN.getValue()) {
            return ResponseUtils.warn("未加入运行的任务无法移除");
        }
        timerJob.setState(TimerJob.Status.NO_JOIN.getValue());

        /*ScheduleJob scheduleJob = FastJsonUtils.jsonToObj(timerJob.toString(), ScheduleJob.class);
        try {
            scheduleManager.deleteJob(scheduleJob);
        } catch (SchedulerException e) {
            e.printStackTrace();
            return ResponseUtils.warn("移除调度任务失败");
        }*/
        timerJobService.modify(timerJob);
        return ResponseUtils.success("移除调度任务成功");
    }

    /**
     * 获取容器中计划的任务
     *
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "/web/timerJob/planList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response planList(HttpServletRequest request, HttpServletResponse response) {
        List<ScheduleJob> list = new ArrayList<>();
        try {
            list = scheduleManager.getAllJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return ResponseUtils.success(new Page<ScheduleJob>(list));
    }*/

    /**
     * 获取容器中正在运行中的任务
     *
     * @param request
     * @param response
     * @return
     */
    /*@RequestMapping(value = "/web/timerJob/runList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response runList(HttpServletRequest request, HttpServletResponse response) {
        List<ScheduleJob> list = new ArrayList<>();
        try {
            list = scheduleManager.getRunningJob();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return ResponseUtils.success(new Page<ScheduleJob>(list));
    }*/
}
